import type { PopupProps, PopupAction, UsePopupReturnType } from '../types/popup';
import type { DynamicProps } from '#/utils';
import { getDynamicProps } from '@/utils';
import { error } from '@/utils/log';

type Props = Partial<DynamicProps<PopupProps>>;

export function usePopup(props?: Props): UsePopupReturnType {

    const popupRef = ref<Nullable<PopupAction>>(null);
    const loadedRef = ref<Nullable<boolean>>(false);

    async function getPopup() {
        const popup = unref(popupRef);
        if (!popup) {
            error('弹出组件实例尚未获取，请确保在执行打开弹出层操作时已呈现弹出层组件！');
        }
        await nextTick();
        return popup as PopupAction;
    }

    function register(instance: PopupAction) {
        onUnmounted(() => {
            popupRef.value = null;
            loadedRef.value = null;
        });

        if (unref(loadedRef) && instance === unref(popupRef)) return;

        popupRef.value = instance;
        loadedRef.value = true;

        watch(() => props, () => {
            props && instance.setProps(getDynamicProps(props));
        },{
            immediate: true,
            deep: true,
        });
    }

    const methods: PopupAction = {
        openPopup: async () => {
            const form = await getPopup();
            await form?.openPopup();
        },
        closePopup: async () => {
            const form = await getPopup();
            await form?.closePopup();
        },
        openPopupLoading: async () => {
            const form = await getPopup();
            await form?.openPopupLoading();
        },
        closePopupLoading: async () => {
            const form = await getPopup();
            await form?.closePopupLoading();
        },
        setProps: async (popupProps: Partial<PopupProps>) => {
            const form = await getPopup();
            form.setProps(popupProps);
        },
    };

    return [register, methods];
}